import { existsSync, readFileSync, writeFileSync } from "fs";
import { join } from "path";
import * as rimraf from 'rimraf';
import { cpDir } from "../utils/FileUtil";
import { PublishLaya2Base } from "./PublishLaya2Base";

export class BaiDuPublish extends PublishLaya2Base {
    get projDir() { return "bdgame" };
    get libJs(){return "laya.bdmini.js"};
    createProject() {
        let toPath = this.mProjPath
        if (existsSync(toPath)) {
            this.doPack();
            return;
        }
        this.log('创建项目目录:' + toPath);

        let tplPath = this.mTempProjPath
        rimraf(toPath, (err2) => {
            if (err2) {
                console.warn(`清理目录${toPath}出错`);
                return;
            }

            cpDir(tplPath, toPath, () => {
                let projCfgPath = join(toPath, 'project.swan.json');
                let fstr = readFileSync(projCfgPath).toString();
                fstr = fstr.replace(/\$\{APPID\}/g, this._publishVo.content.appId);
                fstr = fstr.replace('${PORJECT_NAME}', encodeURI(this._publishVo.name));
                writeFileSync(projCfgPath, fstr);

                this.log('项目生成完毕 下一步可以开始打包游戏了');
                this.doPack();
            });
        });
    }

    async doPack() {
        await this.buildProject();
        this._convertIndex();
        this.packOver();
    }
    
    private _convertIndex(){
        // vivo项目，修改index.js
        let filePath = join(this.mProjPath, "index.js");
        if (!existsSync(filePath)) {
            return;
        }
        let fileContent = readFileSync(filePath, "utf8");
        fileContent = fileContent.replace(/loadLib(\(['"])/gm, "require$1./");
        writeFileSync(filePath, fileContent, "utf8");
    }
}